<?php

namespace App\Admin\Models;

use Encore\Admin\Facades\Admin;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\MessageBag;
use Ixudra\Curl\Facades\Curl;
use Illuminate\Pagination\LengthAwarePaginator;

class StoreInnerSales extends BaseModel
{
    protected $table = 'store_inner_sales';
    //指定主键
    protected $primaryKey = 'sisId';

    public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
    {
        $perPage = Request::get('per_page', 20);

        $page = Request::get('page', 1);
        $sgName = urlencode(Request::get('sgName'));

        $start = ($page-1)*$perPage;

        ///////获取数据//////////////////////////////////////////////////////////////////////////////////////
        $sId = Admin::user()->sId;

        $url = $this->host."/storeInnerSales/getList?page={$page}&perPage={$perPage}&scKey={$sId}&sgName={$sgName}";

        $response = Curl::to($url)->get();
        $data = $this->handelApiData($response);

        ////////获取数据/////////////////////////////////////////////////////////////////////////////////////
//        $data = [
//            'count' => 2,
//            'data' => [
//            [
//                "sisId"=> 35,
//                "scId"=> 2,
//                "sId"=> 2,
//                "sgName"=> "Sfaf胜多负少的",
//                "sgLogo"=> "http:\/\/images.common.think1st.cn\/images\/f3d81342211a6d916ae0fa54ac77b55f.jpg",
//                "goodsNum"=> "2",
//                "userName"=> '刘德华',
//                "createUser"=> "system",
//                "createTime"=> "2019-06-08 20:43:18",
//                "updateUser"=> null,
//                "updateTime"=> null]
//            ],
//            [
//                "sisId"=> 36,
//                "scId"=> 2,
//                "sId"=> 2,
//                "sgName"=> "打发士大夫撒",
//                "sgLogo"=> "http:\/\/images.common.think1st.cn\/images\/f3d81342211a6d916ae0fa54ac77b55f.jpg",
//                "goodsNum"=> "2",
//                "userName"=> '刘德华',
//                "createUser"=> "system",
//                "createTime"=> "2019-06-08 20:43:18",
//                "updateUser"=> null,
//                "updateTime"=> null
//            ],
//        ];
        $total = $data['count'];

        extract($data['data']);

        $tags = static::hydrate($data['data']);

        $paginator = new LengthAwarePaginator($tags, $total, $perPage);

        $paginator->setPath(url()->current());

        return $paginator;
    }

    public static function with($relations)
    {
        return new static;
    }

    /**
     * Add a basic where clause to the query.
     *
     * @param  string|array|\Closure  $column
     * @param  mixed   $operator
     * @param  mixed   $value
     * @param  string  $boolean
     * @return $this
     */
    public function where($column, $operator = null, $value = null, $boolean = 'and'){
        // http://localhost:96/admin/remark/remarkTag?rtcId=1
        // $column rtcId
        // $operator 1
        // $value null
        // $boolean and
        return $this;
    }

    // 获取单项数据展示在form中
//    public function findOrFail($id)
//    {
//        $sId = Admin::user()->sId;
//        $url = $this->host."/storeGoods/get/{$id}?mcKey=".$sId;
//        $response = Curl::to($url)->get();
//        $data = $this->handelApiData($response);
//        $data = [
//            "sisId"=> 36,
//            "scId"=> 2,
//            "sId"=> 2,
//            "sgName"=> "打发士大夫撒",
//            "sgLogo"=> "http:\/\/images.common.think1st.cn\/images\/f3d81342211a6d916ae0fa54ac77b55f.jpg",
//            "goodsNum"=> "2",
//            "userName"=> '刘德华',
//            "createUser"=> "system",
//            "createTime"=> "2019-06-08 20:43:18",
//            "status"=> "0",
//            "updateUser"=> null,
//            "updateTime"=> null
//        ];
//        return static::newFromBuilder($data);
//    }

    // 保存提交的form数据
//    public function save(array $options = Array())
//    {
//
//        $attributes = $this->getAttributes();
//        $userName = Admin::user()->name;
//        // 根据是否有id判断添加还是更新
//        if (isset($attributes['sgId'])){
//            $ignore = ['sgNum','createUser', 'createTime', 'updateUser', 'updateTime'];
//            $newAttributes = array();
//            foreach($attributes as $key => $value){
//                if (!in_array($key, $ignore)){
//                    $newAttributes[$key] = $value;
//                }
//            }
//
//            $newAttributes['updateUser'] = $userName;
//            $url = $this->host."/storeGoods/edit";
//        }else{
//            $ignore = ['createUser', 'createTime', 'updateUser', 'updateTime'];
//            $newAttributes = array();
//            foreach($attributes as $key => $value){
//                if (!in_array($key, $ignore)){
//                    $newAttributes[$key] = $value;
//                }
//            }
//
//            $newAttributes['createUser'] = $userName;
//            $url = $this->host."/storeInnerSales/add";
//        }
//
//        $sId = Admin::user()->sId;
//        $newAttributes['scKey'] = $sId;
//        $newAttributes['auCode'] = Admin::user()->auCode;
//        // 如果是店长直接同意了
//        $newAttributes['status'] = 0;
//        if(Admin::user()->isRole('manager')){
//            $newAttributes['status'] = 10;
//        }
//        $response = Curl::to($url)
//            ->withData($newAttributes)
//            ->post();
//
//        $data = json_decode($response, true);
//
//        if (!isset($data['code'])){
//            $error = new MessageBag([
//                'title'   => '系统错误',
//                'message' => '',
//            ]);
//
//            return back()->with(compact('error'));
//        }
//        if ($data['code'] == 0){
//
//            $error = new MessageBag([
//                'title'   => '保存失败',
//                'message' => $data['msg'],
//            ]);
//
//            return back()->with(compact('error'));
//
//        }else{
//
//            $success = new MessageBag([
//                'title'   => '保存成功',
//                'message' => $data['msg'],
//            ]);
//
//            return back()->with(compact('success'));
//        }
//
//        return $this;
//    }

    // 重写此方法，因为删除前要调用。不写则报错
    public function find($id){
        $this->sgId = $id;
        return $this;
    }

    // 重写删除方法
    public function delete(){

        $attributes = $this->getAttributes();

        $remarkKey = config('services.extend.remarkKey');
        $remarkHost = config('services.extend.remarkHost');
        $url = $remarkHost.'/api/remark/delTag';

        // 请求外部数据
        $Functions = new Functions();
        $attributes['rcKey'] = $remarkKey;

        $data = $Functions->Post($url, $attributes);
        $data = json_decode($data, true);
        if (!isset($data['code'])){
            $error = new MessageBag([
                'title'   => '系统错误',
                'message' => '',
            ]);

            return back()->with(compact('success'));
        }
        if ($data['code'] == 0){
            // 抛出错误信息
            $this->saving(function ($form) {

                $error = new MessageBag([
                    'title'   => '保存失败',
                    'message' => $data['msg'],
                ]);

                return back()->with(compact('error'));
            });
        }else{
            // 抛出错误信息
            $this->saving(function ($form) {

                $error = new MessageBag([
                    'title'   => '保存成功',
                    'message' => $data['msg'],
                ]);

                return back()->with(compact('success'));
            });
        }

        return $this;
    }

}
